﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using ControlCenter.Model;
using ControlCenter.Model.BizEntities;
using ControlCenter.Model.WebApiDto;
using Dapper;

namespace ControlCenter.Data
{
    /// <summary>
    /// 应用包配置仓储类
    /// </summary>
    public class PackageConfigRepository : RepositoryBase, IPackageConfigRepository
    {

        public async Task<bool> Add(PackageConfigItem item)
        {
            string sql = @"
INSERT INTO [dbo].[PackageConfig]
           ([PackageId]
           ,[Name]
           ,[Type]
           ,[DefaultValue]
           ,[Value]
           ,[Remark]
           ,[Sequence]
           ,[IsRequired]
           ,[IsSystem])
     VALUES
           (@PackageId
           ,@Name
           ,@Type
           ,@DefaultValue
           ,@Value
           ,@Remark
           ,@Sequence
           ,@IsRequired
           ,@IsSystem)";
            return await ControlCenterDbConn.ExecuteAsync(sql, item) > 0;
        }

        /// <summary>
        /// 查询指定应用包的参数配置
        /// </summary>
        /// <param name="packageId"></param>
        /// <returns></returns>
        public async Task<IEnumerable<PackageConfigItem>> Query(Guid packageId)
        {
            string sql = @"SELECT * FROM PackageConfig WHERE PackageId=@PackageId ORDER BY Sequence ASC";
            return await ControlCenterDbConn.QueryAsync<PackageConfigItem>(sql, new { PackageId = packageId });
        }

        /// <summary>
        /// 更新应用包的参数配置
        /// </summary>
        /// <param name="packageConfigItem"></param>
        /// <returns></returns>
        public async Task<bool> Update(PackageConfigItem packageConfigItem)
        {
            string sql = @"
UPDATE [dbo].[PackageConfig]
   SET 
      [Value] = @Value
      ,[Sequence] = @Sequence
 WHERE [PackageConfigId] = @PackageConfigId";
            return await ControlCenterDbConn.ExecuteAsync(sql, packageConfigItem) > 0;
        }

        /// <summary>
        /// 删除应用包下的所有参数配置
        /// </summary>
        /// <param name="packageId"></param>
        /// <returns></returns>
        public async Task<bool> DeleteByPackageId(Guid packageId)
        {
            string sql = @"DELETE PackageConfig WHERE PackageId=@PackageId";
            return await ControlCenterDbConn.ExecuteAsync(sql, new { PackageId = packageId }) > 0;
        }
    }
}
